<?php 
if(!defined('IN_OPEN')) exit('no access');
if(!defined('OPEN_ROOT')) define('OPEN_ROOT',dirname(dirname(dirname(__FILE__))));
require_once OPEN_ROOT.'/lib/class/db.class.php';
require_once OPEN_ROOT.'/lib/class/memcached.class.php';
require_ONCE OPEN_ROOT.'/lib/function/core.func.php';
class appscore
{
	/**
	 * app评分类
	 *
	 */
	public function __construct($appid)
	{
		if(empty($appid) || !is_numeric($appid)) exit('appid param error');
		if(empty($oauth_dbhost)) include  OPEN_ROOT.'/config.inc.php';
		$this->db = db::connect($oauth_dbhost,$oauth_dbuser,$oauth_dbpw,$oauth_dbname);
		$this->mem = new Memcached();
		$this->appid = intval($appid);
	}
	/**
	 * 评分操作
	 */
	public function addScore($tyid,$score)
	{
		if(empty($tyid)) return false;
		$tyid = intval($tyid);
		$score = intval($score);
		$ip = getip();
		$sql = "replace into tyopen_appscore(appid,tyid,score,ip) values($this->appid,$tyid,$score,'$ip')";
		$result = $this->db->query($sql);
		if($result==false)
		{
			$data = array('result'=>-1,
						  'data'=>false,
						  'msg'=>'数据库操作错误'
			);
			return $data;
		}
		$this->getScoreList(false);
		return array('result'=>1,
						  'data'=>$result,
						  'msg'=>'操作成功'
			);
	}
	/**
	 * 判断该用户是否对该应用评分过
	 */
	public function isScored($tyid)
	{
		if(empty($tyid)) return false;
		$scorelist = $this->getScoreList($this->appid);
		//print_r($scorelist);
		foreach ($scorelist as $value)
		{
			if($value['tyid']==$tyid) return true;
		}
		return false;
	}
	/**
	 * 获取该应用的平均分
	 */
	public function getAverageScore()
	{
			$cachekey = md5($this->appid.'_appaveragescore');
			$averagescore = $this->mem->get($cachekey);
			//$averagescore = false;
			if($averagescore==false)
			{
				$scorelist = $this->getScoreList();
				$allscore = 0;
				foreach ($scorelist as $key=>$value)
				{
					$allscore+=$value['score'];
				}
				$n = count($scorelist);
				if($n!==0)
				{
					$score = $allscore/$n;
				}
				else $score=0;
				$averagescore = round($score);
				$this->mem->set($cachekey,$averagescore,3600);
			}
			return $averagescore;
			
	}
	public function getScoreList($cacheflag=true)
	{
		$cachekey = md5($this->appid.'_appscorelist');
		$list = $this->mem->get($cachekey);
		if($list==false || $cacheflag==false)
		{
			$sql = "select tyid,appid,score from tyopen_appscore where appid=".$this->appid;
			$list = $this->db->fetchAll($sql);
			$this->mem->set($cachekey,$list,86400);
		}
		return $list;
	}
	
}
?>